<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/8/13
 * Time: 15:00
 */

namespace app\redis\controller;


use think\App;
use think\Controller;

class Hash extends Controller
{
    private $redis;
    public function __construct(App $app = null)
    {
        parent::__construct($app);
        $this->redis =  new \Redis();
        $this->redis->connect('127.0.0.1',6379);
    }

    // 设置 如果成功 返回1 失败返回0 覆盖 返回0
    public function hset()
    {
        $this->redis->hset('1','name','康凯');
        $this->redis->hset('1','age','99');
        $this->redis->hset('1','sex','男');
        $this->redis->hset('1','num','36');
    }

    public function hget()
    {
        $res = $this->redis->hGet('1','num');
        dump($res);
    }

    // 获取key中所有的值
    public function hvals()
    {
        $res = $this->redis->hVals('1');
        dump($res);
    }

    // 获取hash中所有的keys
    public function hkeys()
    {
        $arr = $this->redis->hKeys('1');
        dump($arr);
    }
    //获取一个hash中所有的key和value 顺序是随机的
    public function hgetall()
    {
        $arr = $this->redis->hGetAll('3');
        dump($arr);
    }

    //获取hash中key的数量
    public function hlen()
    {
        return $this->redis->hLen('1');
    }

    public function hsetnx()
    {
        $set1 = $this->redis->hSetNx('1','name','李四');
        if($set1){
            $res1 = $this->redis->hGet('1','name');
            dump($res1);
        }else{
            echo "出错了";
        }

        $set2 = $this->redis->hSetNx('2','name','王五');
        if($set2){
            $res2 = $this->redis->hGet('2','name');
            dump($res2);
        }else{
            echo "出错了";
        }
    }

    // 判断一个hash是否存在
    public function hexisys()
    {
        echo $this->redis->hExists('1','name');
    }

    public function hdel()
    {
        $this->redis->hDel('1','name');
    }
    // 批量设置多个key的值
    public function hmset()
    {
        $arr = [
            'name'=>'钱多多',
            'age'=>16,
            'sex'=>'男',
            'num'=>2
        ];

        $this->redis->hMset('3',$arr);
    }
    // 批量获取多个key的值
    public function hmget()
    {
        $arr = [
            'name',
            'num'
        ];

        $res = $this->redis->hMGet('3',$arr);
        dump($res);
    }

    // 给一个键值，file 增加整数值
    public function hincrby()
    {
        return $this->redis->hIncrBy('3','age',3);
    }
    // 给一个键值，file 增加浮点数的值
    public function hincrfloat()
    {
        return $this->redis->hIncrByFloat('3','age',3.5);
    }
}